﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;

namespace RoMFramework.Packets
{
    public class PacketManager
    {
        public static int SendPacketCount, RecvPacketCount;

        public static string FormatPacketToString(byte[] packet)
        {
            //string lines = "00000000";
            string hex = "";
            string text = "";
            int rows = -1;
            string finalresult = "";

            for (int i = 0; i < packet.Length; i++)
            {
                hex += packet[i].ToString("X2") + " ";
                //text += ((char)packet[i] != 0) ? (char)packet[i] : '.';
                if (packet[i] >= ' ' && packet[i] <= '~')
                {
                    text += (char) packet[i];
                }
                else
                {
                    text += '.';
                }

                double newline = (double)(i + 1) / 16d;
                newline -= Math.Floor(newline);

                if (newline == 0)
                {
                    rows += 1;
                    finalresult += String.Format("{0}   {1}   {2}\r\n", (rows * 16).ToString("X8"), hex, text);
                    hex = "";
                    text = "";
                }
            }
            return finalresult;
        }

        public static void WritePacketToStream(StreamWriter streamWriter, byte[] packet)
        {
            streamWriter.WriteLine();
            //streamWriter.Write("Size = {0}, Count = {1}, Suspected packet type = {2}",
                                   //RoMFramework.Utilities.BytetoString(Utilities.GetSubByteArray(packet, 0x08, 0x04)), PacketCounter, "Null");
            streamWriter.WriteLine(FormatPacketHeaderInfoToString(packet));
            streamWriter.WriteLine();
        }

        public static string FormatPacketHeaderInfoToString(byte[] packet)
        {
            return String.Format("Size = {0}, Count = {1}, Suspected packet type = {2}",
                                 RoMFramework.Utilities.BytetoString(Utilities.GetSubByteArray(packet, 0x08, 0x04)),
                                 SendPacketCount, "Null");
        }

        public static string FormatPacketHeaderInfoToString(PacketBase p)
        {
            return String.Format("Size = {0}, Count = {1}, Suspected packet type = {2}",
                                 p.Size,
                                 SendPacketCount, p.Content);
        }

        public static PacketBase ParsePacket(Byte[] b, Direction d)
        {
            return new PacketBase(b, d);
        }

        public static void GetByteArrayFromPointer(IntPtr bufferptr, uint size, out byte[] b)
        {
            b = new byte[size];
            Marshal.Copy(bufferptr, b, 0, (int)size);
        }
    }
}
